// 获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    model: {},
    maxFiles: 3,
    files: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadDetail();
  },
  loadDetail() {
    let _this = this;
    app.ajax({
      url: 'Maintenance/Add',
      success(resp) {
        if (resp.model) {
          _this.setData({
            model: resp.model,
          });
        }
      }
    });
  },
  addImage(e) {
    let _this = this;
    wx.chooseMedia({
      mediaType: ['image'],
      sourceType: ['camera'],
      sizeType: ['compressed'],
      success: function (res) {
        let _files = _this.data.files;
        if (res.tempFiles.length + _files.length > _this.data.maxFiles) {
          wx.showToast({
            icon: 'none',
            title: `最多允许上传${_this.data.maxFiles}张图片`
          });
          return;
        }
        let startIdx = _files.length;
        for (let i = 0; i < res.tempFiles.length; i++) {
          _files.push({
            img: res.tempFiles[i].tempFilePath,
            percent: 0,
            id: 0,
            unique: startIdx + i
          });
        }
        _this.setData({
          files: _files
        }, function () {
          for (let j = 0; j < res.tempFiles.length; j++) {
            _this.uploadImg(res.tempFiles[j].tempFilePath, startIdx + j);
          }
        });
      }
    });
  },
  uploadImg(file, idx) {
    let _this = this;
    var task = wx.uploadFile({
      url: `${app.apiRoot}/Picture/AsyncUpload`,
      filePath: file,
      name: 'qqfile',
      success(resp) {
        var data = JSON.parse(resp.data) //返回的是[字符串]，需要自己转为JSON格式
        let _files = _this.data.files;
        _files[idx].id = data.pictureId;
        _this.setData({
          files: _files
        });
      },
      fail(resp) {
        console.log('fail', resp);
      }
    });

    task.onProgressUpdate((res) => {
      let _files = _this.data.files;
      _files[idx].percent = res.progress;
      _this.setData({
        files: _files
      });
    });
  },
  tapImg(e) {
    let _this = this;
    let _idx = e.currentTarget.dataset.idx
    let _files = _this.data.files;
    _files.splice(_idx, 1);
    _this.setData({
      files: _files
    });
  },
  onChange(e) {
    let _this = this;
    const {
      detail
    } = e;
    const {
      model
    } = _this.data;
    model.Comment = detail;
    this.setData({
      model
    });
  },
  doSave(e) {
    let _this = this;
    const {
      model
    } = _this.data
    let _imgs = '';
    let _picDone = true;
    for (let i = 0; i < _this.data.files.length; i++) {
      if (_this.data.files[i].id <= 0) {
        _picDone = false;
        break;
      } else {
        _imgs += ',' + _this.data.files[i].id;
      }
    }
    if (!_picDone) {
      app.showNotify('请等待图片上传完成');
      return;
    }
    model.SelectedPictureIds = _imgs;
    if (!model.Comment) {
      app.showNotify('请输入情况说明');
      return;
    }
    if (model.Comment.length>50) {
      app.showNotify('情况说明不能大于50字符');
      return;
    }
    app.ajax({
      url: 'Maintenance/SaveAdd',
      data: model,
      timeout: 2000,
      again: false, // 重复调用
      verifyToken: true,
      success: function (resp) {
        if (!resp.result) {
          app.showNotify(resp.msg);
        } else {
          wx.showToast({
            title: '报修成功',
            complete() {
              wx.navigateBack({
                delta: 1
              });
            }
          });
          if (resp.id > 0) {
            wx.request({
              url: `${app.apiRoot}/Maintenance/SubscribeMessage`,
              method: 'POST',
              data: {
                id: resp.id,
                templateId: 'nQpdDl04GLhjY7EwrF3rk6orDUEI_WcDQ3lp5FUg09k'
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success(msgRes) {
                console.log(msgRes.data);
                // if (msgRes.data.success) {
                //   wx.showModal({
                //     title: '操作成功！',
                //     content: msgRes.data.msg,
                //   })
                // } else {
                //   wx.showModal({
                //     title: '操作失败！',
                //     content: msgRes.data.msg,
                //   })
                // }
              }
            })
          }
        }
      }
    });
  },
  doBack(e) {
    wx.navigateBack({
      delta: 1
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 输入框值变化
  onFieldChange(e) {
    const _this = this;
    const {
      filter
    } = _this.data;
    const {
      detail,
      target: {
        id
      }
    } = e;
    filter[id] = detail;
    this.setData({
      filter
    });
  },

  // 输入框值变化
  onSwitchChange(e) {
    const _this = this;
    const {
      filter
    } = _this.data;
    const {
      detail,
      target: {
        id
      }
    } = e;
    filter[id] = detail;
    this.setData({
      filter
    });
  },
})